package gov.pbc.nn.kjgl.software.handle;

import gov.pbc.nn.core.bdf.entity.Dept;
import gov.pbc.nn.core.bdf.entity.User;
import gov.pbc.nn.core.bdf.service.DeptService.DefaultDeptRowMapper;
import gov.pbc.nn.core.dao.PbcnnCoreJdbcDao;
import gov.pbc.nn.core.utils.SecurityUtils;
import gov.pbc.nn.kjgl.Constants;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.bstek.bdf2.core.business.IDept;
import com.bstek.bdf2.core.business.IUser;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.uflo.client.service.ProcessClient;
import com.bstek.uflo.env.Context;
import com.bstek.uflo.model.ProcessInstance;
import com.bstek.uflo.process.handler.AssignmentHandler;
import com.bstek.uflo.process.node.TaskNode;

@Component("ywgxDeptAssignmentHandler")
public class YwgxDeptAssignmentHandler implements AssignmentHandler {

	@Autowired
	@Qualifier(ProcessClient.BEAN_ID)
	private ProcessClient processClient;

	@Override
	public Collection<String> handle(TaskNode taskNode, ProcessInstance processInstance, Context context) {

		String username = processClient.getProcessVariable("ywgxKz", processInstance).toString();
		String sql = "SELECT\n" + "		d.*\n" + "	FROM\n" + "		t_dept d\n"
				+ "	INNER JOIN bdf2_user_dept ud ON d.ID_ = ud.DEPT_ID_\n" + "	WHERE\n" + "		ud.USERNAME_ = ?";
		PbcnnCoreJdbcDao jdbc = ContextHolder.getBean(PbcnnCoreJdbcDao.BEAN_ID);
		List<IDept> depts = jdbc.getJdbcTemplate().query(sql, new String[] { username }, new DefaultDeptRowMapper());
		if (depts.isEmpty()) {
			return null;
		}
		Dept dept = (Dept) depts.get(0);

		List<IUser> ls = SecurityUtils.getUserByRoleForDept(dept.getCDept().getId(), Constants.ROLE_CZ);
		List<String> users = new ArrayList<String>();
		for (IUser u : ls) {
			users.add(u.getUsername());
		}
		return users;
	}

}
